//
//  MMColorBar.m
//  MemeMaker
//
//  Created by Phan Quang Ha on 7/13/13.
//  Copyright (c) 2013 soyo. All rights reserved.
//

#import "MMColorBar.h"
#import "MMUtils.h"

@interface MMColorBar ()
{
    UIView *pointerView;
}

@end

@implementation MMColorBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        pointerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 16, 16)];
        [pointerView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"target_point.png"]]];
        pointerView.hidden = YES;
        [self addSubview:pointerView];
    }
    return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        pointerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 16, 16)];
        [pointerView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"target_point.png"]]];
        pointerView.hidden = YES;
        [self addSubview:pointerView];
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    UIImage *imgColorBar = [UIImage imageNamed:@"color_bar.png"];
    [imgColorBar drawInRect:self.bounds];
}

#pragma mark - Touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    pointerView.center = location;
    pointerView.hidden = NO;
    
    UIColor *color = [MMUtils getColorFromImage:[UIImage imageNamed:@"color_bar.png"] atX:location.x andY:location.y];
    
    if (_delegate && [_delegate respondsToSelector:@selector(didSelectColor:)]) {
        [_delegate didSelectColor:color];
    }
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    if ((location.x > 0 && location.x < self.bounds.size.width) && (location.y >0 && location.y < self.bounds.size.height)) {
        pointerView.center = location;
        
        pointerView.hidden = NO;
        UIColor *color = [MMUtils getColorFromImage:[UIImage imageNamed:@"color_bar.png"] atX:location.x andY:location.y];
        if (_delegate && [_delegate respondsToSelector:@selector(didSelectColor:)]) {
            [_delegate didSelectColor:color];
        }
    }
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    pointerView.hidden = YES;
    UIColor *color = [MMUtils getColorFromImage:[UIImage imageNamed:@"color_bar.png"] atX:location.x andY:location.y];
    
    if (_delegate && [_delegate respondsToSelector:@selector(didSelectColor:)]) {
        [_delegate didSelectColor:color];
    }
}
@end
